﻿using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

public class SpanSceneMoveLogic
{
    private static SpanSceneMoveLogic self;
    private ScenePlayerLogic scenePlayerLogic;

    private bool finishSwitch = false;

    private ModelLocator model;
    private MySocket mySocket;
    private GameObject findNpc;

    private string objID;

    public static SpanSceneMoveLogic getInstance()
    {
        if(self == null)
        {
            self = new SpanSceneMoveLogic();
        }
        return self;
    }

    public SpanSceneMoveLogic()
    {
        model = ModelLocator.getInstance();
        mySocket = MySocket.getInstance();
        scenePlayerLogic = Camera.mainCamera.GetComponent<ScenePlayerLogic>();

        model.addEventListener(23123, onSwitchScene);//切换场景//
        model.addEventListener(2312, completeScene);

        mySocket.addEventListener(1112, autoFoundWay);//服务器寻路消息//
    }

    /// <summary>
    /// 切场景
    /// </summary>
    private void onSwitchScene(object o, DispatchEventArgs e)
    {
        finishSwitch = false;
    }

    private void completeScene(object o, DispatchEventArgs e)
    {
        finishSwitch = true;
    }

    /// <summary>
    /// 服务器返回对应的sceneID,objID
    /// </summary>
    private void autoFoundWay(object o, DispatchEventArgs e)
    {
        ByteArrayEx byteArr = new ByteArrayEx(e.data[0] as byte[]);
        string sceneID = byteArr.readMultiByteEx();
        objID = byteArr.readMultiByteEx();

        startFindWay(sceneID,objID);
    }

    private void startFindWay(string sceneId,string objID)
    {
        //同场景//
        if(PlayerData.Instance().SceneId.ToString() == sceneId)
        {
            findNpc = scenePlayerLogic.getScenePlayerByID(objID);
            if (findNpc != null)
            {
                SceneClickLogic.getInstance().dispatchSceneObjClick(findNpc);
            }
            else
            {
                model.addEventListener(ClientToClientFlag.SERVER_ADD_SCENEOBJ, checkNPC);
            }
        }
    }

    private void checkNPC(object obj ,DispatchEventArgs e)
    {
        GameObject sceneObj = e.data[0] as GameObject;
        if (sceneObj.name == objID)
        {
            model.removeEventListener(ClientToClientFlag.SERVER_ADD_SCENEOBJ);
            SceneClickLogic.getInstance().dispatchSceneObjClick(sceneObj);
        }
    }



}